import {Request} from "../../utils/request";
import host from "../../utils/host";
import func from "../../utils/functions";
const Func = new func();
const HostUrl = host.service;
const Requ = new Request();
var app = getApp();
Page({
  data: {
    banner: true,
    hide: true,
    navH: 0,
    autoplay: true,
    interval: 3500,
    duration: 1500,
    swiperCurrent: 0,
    posts_key: [],
    //筛选排序id
    choose_shaixuan: 1,
    //店铺列表
    ShopList:[
      {
        img:'',
        shopname:'鲜一派生鲜',
        shopscore:'4.8',
        shoppeople:'6.8',
        startmoney:'50',
        sendmoney:'1.5',
        sendtime:'30',
        km:'2.3',
        tab1:'领10元券',
        tab2:'满50减25',
        tab3:'',
      }
    ],
	Address:'',
	goodsList:[],
	seckillList:[]
  },
  // 跳转秒杀页面
  GotoPage:function(e){
    return;
    wx.navigateTo({
      url: '../../pages/miaosa/miaosa',
    })
  },
  onLoad: function () {
    // wx.hideShareMenu();
    var number = app.globalData.version
    this.setData({
      navH: app.globalData.navHeight,
    });
    // 轮播图接口
    new Request(HostUrl.HomeBanner).request(
      () => {
        return {
          id: 1,
          number: number,
          openid: app.globalData.openid,
        }
      },
      (res) => {
		  console.log(res)
        this.setData({
          banner: false,
          posts_key: res.data.banners,
          interval: res.data.interval,
          duration: res.data.duration,
          getname: res.data,
          // king: res.data.king
        })
        if (res.data.swiperCurrent) {
          this.setData({
            autoplay: res.data.autoplay,
            swiperCurrent: res.data.swiperCurrent
          })
        }
    });

    // 首页店铺列表接口
    wx.request({
      url: HostUrl.SZXURL + HostUrl.HomeShopList,
      method: 'get',
      data: {
        data:1
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (setData) => {
		  console.log(setData)
        if(!Func.is_var(setData.data, 'data')){
          Requ.showToast('附件无店铺');
          return;
        }
        setData.data.data.map((e)=>{
          e.img = e.shop_logo? HostUrl.HostName + e.shop_logo:'/images/home/rou.jpg';
          e.shopname = e.shop_name; // 店铺名称
          e.shopscore = parseFloat(e.shop_score/100).toFixed(1);  // 商店分数
          e.shoppeople = '6.8'; // 购买人数销量
          e.startmoney = e.shop_mincharge; // 起送价
          e.sendmoney = e.shop_sendprice;   // 配送费
          e.km = '2.3'; 
          e.tab1='领10元券'; 
          e.tab2='满50减25'; 
          e.tab3=''; 
        });
        this.setData({
          ShopList: setData.data.data,
        });
      }
    });
    
    return;
  },
  // 计算距离
  GetKm:function(latitude, longitude){
    this.data.ShopList.map((e)=>{
      e.km = Func.GetAddresKm(latitude, longitude, e.MS_latitude, e.MS_longitude).toFixed(2);
    });
    this.setData({
      ShopList: this.data.ShopList
    });
  },
  onShow:function(){
	  let _this = this
  // 定位权限
  wx.getSetting({
    success: (res)=>{
      if (!res.authSetting['scope.userLocation']) {
        wx.authorize({
          scope: 'scope.userLocation',
          success: ()=>{
            // 获取用户当前地址
            this.GetUserLocation((res)=>{
              let latitude = app.globalData.latitude?app.globalData.latitude:res.latitude;
              let longitude = app.globalData.longitude?app.globalData.longitude:res.longitude;
              let self_site_id = app.globalData.self_site_id;
              this.GetSelfSite(latitude, longitude, self_site_id);
              // 二次计算距离
              this.GetKm(latitude, longitude);
			  this.getData()
            });
          },
          fail: ()=>{
            if (wx.openSetting) {
              this.openSetting();  // 如果没有授权摄像头权限，引导用户开启
            }
            return;              
          },
        });
      }else{
        // 获取用户当前地址
        this.GetUserLocation((res)=>{
          let latitude = app.globalData.latitude?app.globalData.latitude:res.latitude;
          let longitude = app.globalData.longitude?app.globalData.longitude:res.longitude;
          let self_site_id = app.globalData.self_site_id;
          this.GetSelfSite(latitude, longitude, self_site_id);
          // 二次计算距离
          this.GetKm(latitude, longitude);
		  this.getData()
        });
      }
    },
  });
  },
  // 获取用户当前地址
  GetUserLocation:function(callback){  
    wx.getLocation({
      type: 'gcj02',          // wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      altitude: true,         // 传入 true 会返回高度信息，由于获取高度需要较高精确度，会减慢接口返回速度
      isHighAccuracy: true,   // 开启高精度定位
      success: (res) =>{
        callback(res);
        const latitude = res.latitude;            // 纬度，范围为 -90~90，负数表示南纬
        const longitude = res.longitude;          // 经度，范围为 -180~180，负数表示西经
        const speed = res.speed;                  // 速度，单位 m/s
        const accuracy = res.accuracy;            // 位置的精确度
        const altitude = res.altitude;            // 高度，单位 m
        const verticalAccuracy = res.altverticalAccuracyitude;    // 垂直精度，单位 m（Android 无法获取，返回 0）
        const horizontalAccuracy = res.horizontalAccuracy;        // 水平精度，单位 m
        // console.log(res);
      }
    });
    
  },

  // 获取自提点列表
  GetSelfSite: function(lat, lng, self_site_id=false){
    if(lat == false || lng == false){
      var ManageAddressdata = {};
    }else{
      var ManageAddressdata = {
        latitude: lat,
        longitude: lng,
      };
      if(self_site_id){
        ManageAddressdata['self_site_id'] = app.globalData.self_site_id?app.globalData.self_site_id:self_site_id;
      }
    }
    wx.request({
      url: HostUrl.SZXURL + HostUrl.ManageAddress,
      method: 'GET',
      data: ManageAddressdata,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (setData) => {
		  console.log(setData)
        if(setData.data.data.list == undefined || setData.data.data.list.length == 0){
          Requ.showToast('附件暂无提货点');
          return;
        }
		app.globalData.self_site_list = setData.data.data.list
        this.setData({
          list: setData.data.data.list,
        });
        // 获取存储值
        Func.GetSaveStorage('szx', (res)=>{
          if(res == false){
			  /* wx.navigateTo({
				  url:'/pages/select_address/select_address'
			  }) */
            let value = {
              address: setData.data.data.list[0]['address'],
              id: setData.data.data.list[0]['id'],
              juli: setData.data.data.list[0]['juli'],
              latitude: app.globalData.latitude?app.globalData.latitude:setData.data.data.list[0]['latitude'],
              longitude: app.globalData.longitude?app.globalData.longitude:setData.data.data.list[0]['longitude'],
              name: setData.data.data.list[0]['name'],
              user_id: setData.data.data.list[0]['user_id'],
            };
            Func.SaveStoragec('szx', JSON.stringify(value), (res)=>{
              app.globalData.latitude = setData.data.data.list[0]['latitude'];
              app.globalData.longitude = setData.data.data.list[0]['longitude'];
              this.Address = setData.data.data.list[0]['name'];
              console.log(res);
              this.setData({
                Address: this.Address,
              })
            });
          }else{
            let JsonRes = JSON.parse(res);
            this.Address = JsonRes.name;
            app.globalData.latitude = JsonRes['latitude'];
            app.globalData.longitude = JsonRes['longitude'];
            app.globalData.self_site_id = JsonRes['id'];
            console.log(JsonRes)
          }
          this.setData({
            Address: this.Address,
          })
        });
        

      }
    });
  },

  // 授权弹窗
  openSetting() {
    wx.showModal({
      title: '提示', //提示的标题,
      content: '请打开位置权限', //提示的内容,
      showCancel: true, //是否显示取消按钮,
      cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
      cancelColor: '#000000', //取消按钮的文字颜色,
      confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
      confirmColor: '#3CC51F', //确定按钮的文字颜色,
      success: res => {
        if (res.confirm) {
          // openSetting 是需要事件驱动的，保证它的同步性。
          wx.openSetting({
            success(res) {
            },
            fail(res) {
            }
          })
        } else if (res.cancel) {
          Requ.showToast('需要位置权限');
        }
      }
    });
  },
  // 获取当前地址
  GetAddress: function(e){
    wx.getSetting({
      success: (res)=>{
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success: ()=>{
              this.GetAddressInfo();
            },
            fail: ()=>{
              if (wx.openSetting) {
                this.openSetting();  // 如果没有授权摄像头权限，引导用户开启
              }
              return;              
            },
          });
        }else{
          this.GetAddressInfo();
        }
      },
    });
    return;
  },
  // 获取地址详情信息
  GetAddressInfo: function(){
    wx.navigateTo({
      url: '../../pages/select_address/select_address'
    });
    return;
    wx.chooseLocation({
      success: (res)=>{
        this.MS_address = res.address;
        this.MS_latitude = res.latitude;
        this.MS_longitude = res.longitude;
        this.name = res.name;
        // console.log(res)
        this.setData({
          MS_address: res.address,
        })
      },
    });
  },

  //筛选排序切换
  Shaixuan: function (e) {
    this.setData({
      choose_shaixuan: e.currentTarget.dataset.id
    })
  },

  //跳转至详细页面
  toDetail:function (e) {
    wx.navigateTo({
      url: '../new_shop/new_shop?MS_id=' + this.data.ShopList[e.currentTarget.dataset.index].shop_id,
    })
  },

  
  clicks() {
    var that = this;
    new Request(HostUrl.HomeDiscount).request(
      () => {
        return {
          id: 1
        }
      },
      (res) => {
        if (res.data.user_state == 1) {
          that.setData({
            showModal: false
          })
        }
        that.setData({
          do: res.data,
        })
      })
  },

  click: function () {
    var that = this;
    var show;
    wx.scanCode({
      success: (res) => {
        if (res.result.substr(0, 45) == "https://zyfuns.com/class/scanLogin.cls.php?s=") {
          wx.navigateTo({
            url: '../pclogin/pclogin?sess=' + res.result.substring(45)
          })
        } else {
          wx.showToast({
            title: '二维码无效',
            icon: 'none',
          })
        }
      },
      fail: (res) => {},
      complete: (res) => {}
    })
  },


  bindViewTap: function (e) {
    if (e.currentTarget.dataset.url != "#") {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },
  gotonews: function (e) {
    wx.navigateTo({
      url: '../noticeinfo/noticeinfo?id=' + e.currentTarget.dataset.id
    })
  },
  gotorepair: function (event) {
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
    return;
    wx.navigateTo({
      url: '../repair/repair'
    })
  },
  gotoclass: function () {
    wx.navigateTo({
      url: '../timetable/timetable'
    })
  },

  gotograde: function () {
    wx.navigateTo({
      url: '../grade/grade'
    })
  },
  gotofood: function (event) {
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
  },
  gotoexpress: function () {
    wx.showModal({
      title: '提示',
      content: '该功能正在等待对接'
    })
  },
  gotocar4: function(event){
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
    return;
  },
  gotocard: function (event) {
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
    return;
    wx.navigateTo({
      url: '../cards/cards'
    })
  },
  gotostore: function (event) {
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
    return;
    if (this.data.king == 5) {
      wx.showModal({
        title: '提示',
        content: '该功能正在等待对接'
      })
    } else {
      wx.navigateTo({
        url: '../stores/stores'
      })
    }
  },
  gotocar: function (event) {
    app.globalData.currentindex = event.currentTarget.dataset.index;
    wx.switchTab({
      url: '/pages/shoplist/shoplist',
    });
    return;
    wx.showModal({
      title: '提示',
      content: '该功能正在等待对接'
    })
  },
	goto:function(e){
		switch(e.currentTarget.dataset.index) {
		     case 0:
		        this.gotofood(e)
		        break;
		     case 1:
		        this.gotostore(e)
		        break;
		     case 2:
		        this.gotorepair(e)
		        break;
			case 3:
			   this.gotocar(e)
			   break;
			case 4:
			   this.gotocar4(e)
			   break;
		} 
	},


  navigateToMiniProgram() {
    wx.navigateToMiniProgram({
      appId: 'wx04b49937f001fb12',
      path: 'pages/index/index',
      extraData: {
        foo: 'bar'
      },
      envVersion: 'develop',
      success(res) {
        // 打开其他小程序成功同步触发
        wx.showToast({
          title: '跳转成功'
        })
      }
    })
  },
  // 弹出层里面的弹窗
  ok: function () {
    this.setData({
      showModal: false
    })
  },
  imgok: function () {
    this.setData({
      showModal: false
    })
  },
  goshop: function (e) {
    // if (e.currentTarget.dataset.state == 2) {
    //   wx.navigateTo({
    //     url: '../shop_details/shop_details?shopid=' + e.currentTarget.dataset.shopid
    //   })
    // } else {
    //   wx.showModal({
    //     title: '提示',
    //     content: '此店已打烊'
    //   })
    // }
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    })
    if (e.currentTarget.dataset.url != null) {
      this.setData({
        showModal: false
      })
    }
  },
  receive: function (e) {
    wx.request({
      url: 'https://apps.zyfuns.com/zyfuns/updata_home_discount.cls.php',
      method: 'POST',
      data: {
        receive_id: e.currentTarget.dataset.receive_id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'cookie': 'PHPSESSID=' + app.globalData.phpsessId
      },
      success: function (res) {
        if (res.data.user_state == 1) {
          that.setData({
            showModal: false
          })
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          })
        }
      }
    })
  },
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current,
    })
  },
  get_index: function (e) {
    this.setData({
      swiperCurrent: e.currentTarget.dataset.index,
    })
  },
  getData:function(){
	  let _this = this
	  wx.request({		//获取商品列表
	  	  url: HostUrl.SZXURL + HostUrl.HomeGoodsList,
	      method: 'get',
	      data: {
	        self_site_id:app.globalData.self_site_id
	      },
	      header: {
	        'content-type': 'application/x-www-form-urlencoded',
	        'openid': app.globalData.openid,
	      },
	  	  success(res){
	  		  console.log(res)
	  		  let length = res.data.data.list.length
	  		  for(let i=0;i<length;i++){
				  if(res.data.data.list[i].MG_sales==null){
					  res.data.data.list[i].MG_sales=0
				  }
	  			  res.data.data.list[i].MG_image = 'https://www.zyfuns.com'+ res.data.data.list[i].MG_image
	  			  res.data.data.list[i].num = 0
	  			  res.data.data.list[i].integerPrice = parseInt(res.data.data.list[i].MG_price)
	  			  let flag = res.data.data.list[i].MG_price.indexOf('.')
	  			  res.data.data.list[i].decimalPrice = res.data.data.list[i].MG_price.substring(flag)
	  			  switch(res.data.data.list[i].MG_stype) {
	  			       case 0:
	  			          res.data.data.list[i].type="新鲜蔬菜"
	  			          break;
	  			       case 1:
	  			          res.data.data.list[i].type="甄选水果"
	  			          break;
	  			       case 2:
	  			          res.data.data.list[i].type="海鲜水产"
	  			          break;
	  					case 3:
	  					   res.data.data.list[i].type="冰冻副食"
	  					   break;
	  					case 4:
	  					   res.data.data.list[i].type="肉禽蛋品"
	  					   break;
	  			  } 
	  		  }
	  		  _this.setData({
	  			  goodsList:res.data.data.list
	  		  })
	  	  }
	  	})
	  	wx.request({		//获取秒杀商品列表
	  		  url: HostUrl.SZXURL + HostUrl.SeckillList,
	  	    method: 'get',
	  	    data: {
	  	      self_site_id:app.globalData.self_site_id
	  	    },
	  	    header: {
	  	      'content-type': 'application/x-www-form-urlencoded',
	  	      'openid': app.globalData.openid,
	  	    },
	  		  success(res){
	  			  console.log(res)
	  			  let length = res.data.data.list.length
	  			  for(let i=0;i<length;i++){
					  if(res.data.data.list[i].MG_sales==null){
					  		res.data.data.list[i].MG_sales=0
					  }
	  				  res.data.data.list[i].MG_image = 'https://www.zyfuns.com'+ res.data.data.list[i].MG_image
	  				  res.data.data.list[i].num = 0
	  				  res.data.data.list[i].integerPrice = parseInt(res.data.data.list[i].final_price)
	  				  let flag = res.data.data.list[i].MG_price.indexOf('.')
	  				  res.data.data.list[i].decimalPrice = res.data.data.list[i].final_price.substring(flag)
	  			  }
	  			  _this.setData({
	  			  	 seckillList:res.data.data.list
	  			  })
	  		  }
	  	})
  },
  add:function(e){
	  console.log(e)
	  let good
	  if(e.target.dataset.index!=undefined){
		  good = this.data.goodsList[e.target.dataset.index]
		  good.num+=1
		  this.setData({
		  	goodsList:this.data.goodsList
		  })
	  }else{
		  good = this.data.seckillList[0]
		  this.data.seckillList[0].num+=1
		  this.setData({
			  seckillList:this.data.seckillList
		  })
	  }
	  let length = app.globalData.shopCart.length
	  let flag = -1
	  for(let i=0;i<length;i++){
		  if(app.globalData.shopCart[i].shopId == good.MG_shopid){
			  flag = i
			  break
		  }
	  }
	  if(flag == -1){
		  new Request('get_shopgoods.cls.php').request(
		    () => {
		      return {
		        shop_id: good.MG_shopid,
		        openid: app.globalData.openid,
		      }
		    },
		    (res) => {
				let shop={}
				shop.shopId = good.MG_shopid
				shop.shopName = res.data.shop.name
				shop.data=[]
				shop.data[0]={}
				shop.optionalnum = 1
				shop.data[0].active = true
				shop.data[0].id = good.MG_id
				shop.data[0].image = good.MG_image
				shop.data[0].name = good.MG_name
				shop.data[0].num = 1
				shop.data[0].optional = 1
				if(e.target.dataset.index!=undefined){
					shop.data[0].addprice = good.MG_price
					shop.data[0].groupprice=good.MG_price
					shop.addprice = good.MG_price
				}else{
					shop.data[0].addprice = good.final_price
					shop.data[0].groupprice=good.final_price
					shop.addprice = good.final_price
				}
				app.globalData.shopCart.push(shop)
		    });
	  }else{
		  let shop = app.globalData.shopCart[flag]
		  let len = shop.data.length
		  flag = -1
		  for(let j=0;j<len;j++){
			  if(shop.data[j].id==good.MG_id){
				  flag = j
				  break
			  }
		  }
		  if(flag == -1){
			  let newGood = {}
			  newGood.active=true
			  newGood.id=good.MG_id
			  newGood.image=good.MG_image
			  newGood.name=good.MG_name
			  newGood.num=1
			  newGood.optional=1
			  if(e.target.dataset.index!=undefined){
				  newGood.addprice=good.MG_price
				  newGood.groupprice=good.MG_price
			  }else{
				  newGood.addprice=good.final_price
				  newGood.groupprice=good.final_price
			  }
			  shop.data.push(newGood)
			  shop.addprice=Number(shop.addprice)
			  newGood.groupprice=Number(newGood.groupprice)
			  shop.addprice+=newGood.groupprice
		  }else{
			  let good=shop.data[flag]
			  good.addprice=Number(good.addprice)
			  good.groupprice=Number(good.groupprice)
			  shop.addprice=Number(shop.addprice)
			  good.groupprice+=good.addprice
			  shop.addprice+=good.addprice
			  good.num++
		  }
	  }
  },
  del:function(e){
	  let good
	  if(e.target.dataset.index!=undefined){
		  good = this.data.goodsList[e.target.dataset.index]
		  if(good.num>0){
		  	good.num-=1
		  }else{
			  return
		  }
		  this.setData({
		  	goodsList:this.data.goodsList
		  })
	  }else{
		  good=this.data.seckillList[0]
		  if(this.data.seckillList[0].num>0){
			  this.data.seckillList[0].num--
		  }else{
			  return
		  }
		  this.setData({
		  	seckillList:this.data.seckillList
		  })
	  }
	  let length = app.globalData.shopCart.length
	  let flag = -1
	  for(let i=0;i<length;i++){
		  if(app.globalData.shopCart[i].shopId == good.MG_shopid){
			  flag = i
			  break
		  }
	  }
	  if(flag == -1){
		  return
		}else{
		  let shop = app.globalData.shopCart[flag]
		  let len = shop.data.length
		  flag = -1
		  for(let j=0;j<len;j++){
			  if(shop.data[j].id==good.MG_id){
				  flag = j
				  break
			  }
		  }
		  if(flag == -1){
			  return
		  }else{
			  let good=shop.data[flag]
			  good.addprice=Number(good.addprice)
			  good.groupprice=Number(good.groupprice)
			  shop.addprice=Number(shop.addprice)
			  good.groupprice-=good.addprice
			  shop.addprice-=good.addprice
			  good.num--
		  }
	  }
  }
})